#!/bin/sh

iptables -D INPUT -p udp -m multiport --dports 500,4500 -m comment --comment "IPSec VPN Server" -j ACCEPT 2> /dev/null
ipsec_nums=$(iptables -t nat -L POSTROUTING 2> /dev/null | grep -c "IPSec VPN Server")
if [ -n "$ipsec_nums" ]; then
	until [ "$ipsec_nums" = 0 ]
	do
		rules=$(iptables -t nat -L POSTROUTING --line-num 2> /dev/null | grep "IPSec VPN Server" |awk '{print $1}')
		for rule in $rules
		do
			iptables -t nat -D POSTROUTING $rule 2> /dev/null
			break
		done
		ipsec_nums=$(expr $ipsec_nums - 1)
	done
fi
nums=$(iptables -L forwarding_rule 2> /dev/null | grep -c "IPSec VPN Server")
if [ -n "$nums" ]; then
	until [ "$nums" = 0 ]
	do
		rules=$(iptables -L forwarding_rule --line-num 2> /dev/null | grep "IPSec VPN Server" |awk '{print $1}')
		for rule in $rules
		do
			iptables -D forwarding_rule $rule 2> /dev/null
			break
		done
			nums=$(expr $nums - 1)
	done
fi

enable=$(uci -q get ipsec.ipsec.enabled)
if [ -n "$enable" -a "$enable" == 1 ]; then
	clientip=$(uci -q get ipsec.ipsec.clientip)
	iptables -t nat -I POSTROUTING -s ${clientip%.*}.0/24 -m comment --comment "IPSec VPN Server" -j MASQUERADE
	iptables -I forwarding_rule -s ${clientip%.*}.0/24 -m comment --comment "IPSec VPN Server" -j ACCEPT
	iptables -I INPUT -p udp -m multiport --dports 500,4500 -m comment --comment "IPSec VPN Server" -j ACCEPT
fi
